//
//  HMUserAccountViewModel.swift
//  CZBKWB31
//
//  Created by Linkon Y on 16/8/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//请求数据 保存数据 获取数据 保存单例对象
class HMUserAccountViewModel: NSObject {
    //全局访问点(单例)
    static let sharedTools:HMUserAccountViewModel = HMUserAccountViewModel()
    //用户信息对象 为了频繁操作沙盒
    var userAccount : HMUserAccount_Model?
    //途径
    let file = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")
    
    //accessToken
    var accessToken: String?{
        
        if userAccount?.access_token != nil {
            //如果返回的时间和当前的时间比 
            if userAccount?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return userAccount?.access_token
            }else{
                return nil
            }
            
        }else{
            //代表用火没有登陆过
            return nil
        }
    }
    //判断用户是否登录过
    var isLogin: Bool {
    
    return accessToken != nil
    
    }
    
    
    
    override init() {
        super.init()
        userAccount = getUserAccount()
    }
}
 // MARK: - 保存数据
extension HMUserAccountViewModel{
    
    //保存对象
    func saveUserAccount(userAccount:HMUserAccount_Model){
        //BUG处理 如果第一次存储成功后 便使用userAccount  为nil 因为第一次单例实例化是走init方法时 对useraccount赋值时从沙盒取得的值为nil 单例只走一次init方法  所以不能再赋值   只能保存对象的时候程序员手动对当前对象赋值
        self.userAccount = userAccount
               //保存对象
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: file)
    }
    //获取对象(又返回值)
    func getUserAccount() -> HMUserAccount_Model?{
          //获取对象
       let res = NSKeyedUnarchiver.unarchiveObjectWithFile(file) as?  HMUserAccount_Model
    
        return res
    }
    
    
    
}

 // MARK: - 请求数据 
extension HMUserAccountViewModel {

    //获取授权
    func getUserAccount(code: String, finish:(isSuccess:Bool) -> ()){
        
        HMNetworkTool.sharedTools.oauthLoadUserAccount(code, success: { (response) in
            //请求成功
            //print("请求成功\(response)")
            guard let res = response as? [String : AnyObject] else{
                finish(isSuccess: false)
                return
            }
            //通过字典创建模型
            let  userAccount = HMUserAccount_Model(dict:res)
            //不会形成循环
            self.getUserInfo(userAccount, finish: finish)
        }) { (error) in
            //请求失败
            print("请求失败\(error)")
            finish(isSuccess: false)
        }
    }
    
    //请求个人信息
    func getUserInfo(userAccount:HMUserAccount_Model,finish:(isSuccess:Bool) -> ()){
        
        HMNetworkTool.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) in
            //判断是否为nil 是否可以转为字典
            guard let res = response  as? [String:AnyObject] else{
                 finish(isSuccess: false)
                return
            }
            //赋值
            userAccount.screen_name = res["screen_name"] as? String
            userAccount.avatar_large = res["avatar_large"] as? String
//            print(userAccount)
            //保存对象
            self.saveUserAccount(userAccount)
            finish(isSuccess: true)
        }) { (error) in
            print("请求失败\(error)")
             finish(isSuccess: false)
            
        }
    }
    
}
